import { createRouter, createWebHashHistory } from 'vue-router'
import { getToken } from '@/utils/auth'
import store from '@/store/index'
const routes = [
  {
    path: '/',
    name: 'index',
    redirect: '/home',
    component: () => import('@/layout/index'),
    children: [
      {
        path: 'home',
        name: 'home',
        component: () => import('@/views/Home')
      },
      {
        path: 'statistics',
        name: 'statistics',
        component: () => import('@/views/Statistics')
      },
      {
        path: 'user',
        name: 'user',
        component: () => import('@/views/User')
      }
    ]
  },
  {
    path: '/navBar',
    name: 'navBar',
    component: () => import('@/layout/NavBar'),
    children: [
      {
        path: 'detail',
        name: 'detail',
        component: () => import('@/views/Detail'),
        meta: {
          title: '账单详情'
        }
      },
      {
        path: 'account',
        name: 'account',
        component: () => import('@/views/Account'),
        meta: {
          title: '账号安全'
        }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
const whiteList = ['/login', '/404', '/401']
router.beforeEach(async (to, from, next) => {
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const info = store.state.userInfo
      if (info) {
        next()
      } else {
        try {
          await store.dispatch('getInfo')
          next({ ...to, replace: true })
        } catch (error) {
          //(token过期等情况)
          await store.dispatch('logout')
          next(`/login`)
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login`)
    }
  }
})
export default router
